package com.panyunting.notepad.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.panyunting.notepad.Api;
import com.panyunting.notepad.R;
import com.panyunting.notepad.adapter.NotePadAdapter;
import com.panyunting.notepad.database.NotepadDao;
import com.panyunting.notepad.javabean.Note;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NotePadActivity extends AppCompatActivity {
    private ListView listView;
    private List<Note> noteList = new ArrayList<>();
    private ImageView addRecord;
    private NotePadAdapter adapter;
    private String TAG = " tag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notepad);
        listView = findViewById(R.id.listview);
        initData();

       //这是实现点击某个条目跳转的功能
       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               //跳转页面到RecordActivity
               Intent intent = new Intent(NotePadActivity.this, RecordActivity.class);
               Note note = noteList.get(position);
               //通过intent传递数据
               intent.putExtra("id", note.getId());
               intent.putExtra("content",note.getContent());
               intent.putExtra("noteTime", note.getNoteTime());
               startActivityForResult(intent,1);
           }
       });
        addRecord = findViewById(R.id.addRecord);
        addRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转页面到RecordActivity
                Intent intent = new Intent(NotePadActivity.this, RecordActivity.class);
                //startActivity(intent);
                startActivityForResult(intent,1);//这个跳转是要回传数据的，但是在我们这里不是为了回传数据，而是为了回调方法
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    JSONArray jsonArray = (JSONArray) msg.obj;
                    Log.d("TAG", "handleMessage: jsonarray" + jsonArray);
                    for (int i =0 ; i < jsonArray.size() ; i ++) {

                        Note note = new Note();
                        note.setContent(jsonArray.getJSONObject(i).getString("content"));
                        note.setNoteTime(jsonArray.getJSONObject(i).getString("create_time"));
                        note.setName(jsonArray.getJSONObject(i).getString("name"));
                        noteList.add(note);
                    }
                    Log.d("TAG", "handleMessage: " + noteList);
                    adapter = new NotePadAdapter(NotePadActivity.this,noteList);
                    listView.setAdapter(adapter);
                    break;
                case 2:
                    break;
                default:
                    break;
            }

        }
    };
    private void initData() {
        OkHttpClient client = new OkHttpClient();
        String uname = getSharedPreferences("info",MODE_PRIVATE).getString("username","");
        Log.d("TAG", "initData: uname:" + uname);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        RequestBody body = RequestBody.create(mediaType, "username=" + uname);
        Request request = new Request.Builder()
                .url(Api.queryBookListServlet)
                .post(body)
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .addHeader("cache-control", "no-cache")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(NotePadActivity.this, "Post Failed", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() { 
                        JSONObject jsonObject1 = JSONObject.parseObject(res);
                        Log.d(TAG, "run: " + jsonObject1.toJSONString());
                        Log.d("TAG", "run: result code is :" +jsonObject1.getIntValue("code"));
                        if(jsonObject1.getIntValue("code")==1 ) {
                            Toast.makeText(NotePadActivity.this,"获取成功",Toast.LENGTH_SHORT).show();

                            Message ms   = new Message();
                            ms.what =1 ;
                            ms.obj = jsonObject1.getJSONArray("data");

                            handler.sendMessage(ms);
                        }else{
                            Toast.makeText(NotePadActivity.this,"获取失败",Toast.LENGTH_SHORT).show();
                        }

                    }
                });
            }
        });
//        NotepadDao dao = new NotepadDao(this);

    }
    //这个方法是startActivityForResult的回调方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //先清空原数据
        noteList.clear();
        initData();

    }
}
